package com.wzdigit.wms.raw.service.backtosap;

import cn.hutool.core.date.DateUtil;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.common.utils.SapWebServiceUtil;
import com.wzdigit.wms.web.service.common.wms2sap.ZDT_MsgHeader;
import com.wzdigit.wms.web.service.wms2sap.storecheckproof.*;
import com.wzdigit.wms.web.service.wms2sap.waitcheckinstore.ZDT_064_ReqRECORDS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
    * 库存盘点凭证获取
    * @return
    * @author shuaic
    * @date 2021/6/18 17:22
*/
@Service
@Slf4j
public class StoreCheckProofBackService {
    @Autowired
    private CodeMappingService codeMappingService;

    @Autowired
    SkuMapper skuMapper ;

    @Autowired
    CodeMappingMapper codeMappingMapper ;

    @Autowired
    WarehouseMapper warehouseMapper ;

    @Value("${sap.web.service.protocol-head}")
    private String protocolHead;

    @Value("${sap.web.service.storeChekcProof-url}")
    private String uri;

    @Value("${wzdigit.web.service.sap.ip}")
    private String ip;


    /*
        * @param aedat 凭证日期
     	* @param factory 工厂
    	* @param whsId 库存地点
    	* @param special 是否是特殊库存
     	* @param saleNo 销售订单 特殊库存时必填
    	* @param saleLineNo 销售订单行项目 特殊库存时必填
    	* @param skuId  物料
    	* @param unit 单位
    	* @param qty  数量
        * @return void  判点凭证
        * @author shuaic
        * @date 2021/6/18 17:29
    */
    public ZDT_071_1_RspRECORDS[] getStoreCheckProof(Date aedat, String factory, Integer whsId, boolean special, String saleNo, String saleLineNo, String skuCode, String unit, String qty){
        //查询SKU
        /*Sku sku = skuMapper.selectById(skuId);
        if(sku==null){
            String message = String.format("未找到ID为【%s】的SKU信息",skuId);
            Shift.fatal(StatusCode.BUSINESS_ERR, message);
        }*/
        //查询仓库
        Warehouse warehouse = warehouseMapper.selectById(whsId);
        CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(factory, warehouse.getWhsCode(), 1);
        List<ZDT_071_1_ReqRECORDS> list = new ArrayList<>();
        ZDT_071_1_ReqRECORDS records = new ZDT_071_1_ReqRECORDS();
        try {
            records.setAEDAT(DateUtil.format(aedat,"yyyyMMdd"));
            records.setWERKS(factory);
            records.setLGORT(codeMapping.getMappingCode());
            records.setSOBKZ(special?"E":"");
            records.setKDAUF(saleNo);
            records.setKDPOS(saleLineNo);
            records.setMATNR(skuCode);
            records.setMEINS(unit);
            records.setMENGE(qty);
            list.add(records);
            return  report(list);
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.BUSINESS_ERR);
            return null;
        }


    }

    public ZDT_071_1_RspRECORDS[] report(List<ZDT_071_1_ReqRECORDS> records) {
        log.info("开始调【SAP库存盘点凭证接口】");
        //发送【向SAP报检】的路径
        String urlString = protocolHead + ip + uri;

        log.info("发送报文的路径:" + urlString);

        ZSI_071_1_WMS2SAP_OutProxy proxy = new ZSI_071_1_WMS2SAP_OutProxy  ();

        proxy.setEndpoint(urlString);

        log.info("ZSI_071_1_WMS2SAP_OutProxy:" + proxy.toString());

        // 消息头
        ZDT_MsgHeader header = SapWebServiceUtil.getHeader();

        log.info("header:" + header);


        //输出请求的核心报文
        try {
            for (ZDT_071_1_ReqRECORDS record : records) {

                //格式化生成的XML报文
                JAXBContext jc = JAXBContext.newInstance(ZDT_071_1_ReqRECORDS.class);
                Marshaller ms = jc.createMarshaller();
                ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                Writer writer = new StringWriter();
                ms.marshal(record, writer);

                log.info("发送报文的核心内容【xml】:" + writer.toString());
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            log.error("转成XML出错");
        }


        ZDT_071_1_Req req = new ZDT_071_1_Req();

        // 消息头
        req.setHEADER(header);
        // 记录
        ZDT_071_1_ReqRECORDS [] reqRECORDS = records.toArray(new ZDT_071_1_ReqRECORDS [records.size()]);
        req.setRECORDS(reqRECORDS);

        ZDT_071_1_Rsp rsp = null;


        try {
            //调接口
            rsp = proxy.ZSI_071_WMS2SAP_Out(req);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        ZDT_071_1_RspRECORDS[] rspArr = rsp.getRECORDS();

        //输出请求的核心报文
        try {
            for (ZDT_071_1_RspRECORDS rspRecordHead : rspArr) {

                //格式化生成的XML报文
                JAXBContext jc = JAXBContext.newInstance(ZDT_071_1_RspRECORDS.class);
                Marshaller ms = jc.createMarshaller();
                ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                Writer writer = new StringWriter();
                ms.marshal(rspRecordHead, writer);

                log.info("【SAP_库存盘点凭证接口】返回报文的核心内容【xml】:" + writer.toString());
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            log.error("转成XML出错");
        }

        return rspArr;
    }

}
